<template>
  <div class="s">
    <a-upload
      :name="props.name"
      :show-upload-list="false"
      :accept="fileType.join(',')"
      :action="props.action"
      :data="props.data"
      :headers="_d.headers"
      :before-upload="beforeUpload"
      @change="handleUploadChange"
    >
      <a-button v-if="!slots.default">导入附件</a-button>
      <slot></slot>
    </a-upload>
    <div v-if="props.list?.length" class="file-list">
      <div v-for="(item, index) in props.list" :key="index" class="item">
        <paper-clip-outlined />
        <div class="link" @click="showLink(item)">{{item[_d.fieldNames.filename]}}</div>
        <delete-outlined v-if="props.showDelete" class="del-icon" @click="deleteLink(index)" />
      </div>
    </div>

    <mFilePreview v-if="props.list.length" ref="mFilePreviewRef"></mFilePreview>
  </div>
</template>

<script setup>
import { reactive, ref, computed, useSlots, watch } from "vue";
import { notification, message } from "ant-design-vue";
import { PaperClipOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import mFilePreview from "@/components/mFilePreview/index.vue";

import { useUserStore } from "@/store/userStore";
const userStore = useUserStore();
const mFilePreviewRef = ref();

const slots = useSlots();
const emit = defineEmits(["update:list", "done","download"]);

const props = defineProps({

  // 接口
  action: {
    type: String,
    default: "",
  },
  // 上传文件参数名
  name: {
    type: String,
    default: 'file'
  },
  // 参数
  data: {
    type: Object,
  },
  // 文件类型
  type: {
    type: [Array, String],
    default() {
      return [
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/pdf",
        "application/vnd.ms-excel.sheet.macroEnabled.12",
        "image/jpeg",
        "image/png",
      ];
    },
  },
  // 文件错误提示
  typeError: {
    type: String,
    default: '仅支持xls、xlsx、doc、docx、pdf、xlsm文件类型上传'
  },
  // 文件大小限制，20M
  limit: {
    type: Number,
    default: 20,
  },
  //是否传token
  isToken:{
    type: Boolean,
    default: true,
  },

  // 列表 ---------- 如果要显示列表，直接设置v-model:list="list"
  list: {
    type: [Array],
    default: () => []
  },
  // 列表显示配置
  fieldNames: {
    type: Object,
    default: () => ({id: 'id',filename: 'filename'})
  },
  // 列表是否显示删除按钮
  showDelete: {
    type: Boolean,
    default: true,
  }
});

const _d = reactive({
  headers: {
    Authorization: "Bearer " + userStore.accessToken,
    accepts: "application/json",
    "Load-Balancer": import.meta.env.VITE_APP_LOCAL_IP,
  },
  typeError:"" , // 类型错误提示

  // 列表配置
  fieldNames: {id: 'id',filename: 'filename'}

});
watch(() => props.fieldNames, (val) => {
  _d.fieldNames = Object.assign(_d.fieldNames, val);
})
if(props.isToken){
  _d.headers = {
    Authorization: "Bearer " + userStore.accessToken,
    accepts: "application/json",
    "Load-Balancer": import.meta.env.VITE_APP_LOCAL_IP,
  }
}else{
  _d.headers = {
    accepts: "application/json",
    "Load-Balancer": import.meta.env.VITE_APP_LOCAL_IP,
  }
}
// 文件上传类型
const fileType = computed(() => {
  let res = props.type;
  let typeError = props.typeError;
  if (typeof res == "string") {
    if (props.type == "excel") {
      res = [
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/wps-office.xlsx",
        "application/wps-office.xls",
      ];
      typeError = "仅支持xls、xlsx文件类型上传"
    } else if (props.type == "image") {
      res = ["image/png", "image/jpeg"];
      typeError = "仅支持png、jpeg、jpg文件类型上传"
    } else if(props.type == "pdf"){
      res = [
       "application/pdf",
      ];
      typeError = "仅支持PDF文件类型上传"
    } else {
      res = [res];
    }
  }
  _d.typeError = typeError;
  return res;
});

// 上传之前验证
function beforeUpload(file) {
  if (fileType.value.indexOf(file.type) == -1) {
    message.error(_d.typeError);
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 <= props.limit;
  if (!isLt2M) {
    message.error("文件不能大于" + props.limit + "MB!");
    return false;
  }
  return true;
}

// 上传完成
function handleUploadChange(info) {
  if (info.file.status !== "uploading") {
  }
  if (info.file.status === "done") {
    console.log("上传成功");
    let response = info.file.response;
    console.log(response, info);
    if(response.code != 200) {
      notification.error({
        message: "提示",
        description: `${response.message}`,
      });
    } else {
      _d.fileName = response?.data?.filename || '';
      console.log(_d.fileName );
      emit("done", {
        res: response,
        info: info
      });
    }
  } else if (info.file.status === "error") {
    console.log(info.file.response, info);
    notification.error({
      message: "提示",
      description: `${info.file.name} 上传失败.`,
    });
  }
}

// 显示
function showLink(item) {
  if(props.handleLink) {
    props.handleLink(item);
  } else {
    mFilePreviewRef.value.show(item[_d.fieldNames.id]);
  }
}

// 删除
function deleteLink(index) {
  let list = [...props.list];
  list.splice(index, 1);
  emit('update:list', list);
}
</script>

<style lang="less" scoped>
.s{
  display: flex;
  flex-direction: column;
}
.m{
  color:#1890FF;
}

.file-list {
  padding-top: 2px;
  .item {
    display:  flex;
    gap: 10px;
    align-items: center;
    margin-top: 8px;
    padding: 0 4px;
    &:hover {
      background: #f5f5f5;
      .link {
        color: #1890FF;
      }
      .del-icon {
        opacity: 1;
      }
    }
    .link {
      width: 0;
      flex: 1;
      cursor: pointer;
    }
    .del-icon {
      opacity: 0;
      transition: opacity .3s;
      cursor: pointer;
    }
  }
}

</style>